package com.bookshop.controller;

import com.bookshop.model.Message;
import com.bookshop.model.OrderItemModel;
import com.bookshop.model.OrdersModel;
import com.bookshop.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Controller
public class AddCarController {
    @Autowired
    private CartService cartService;
    @ResponseBody
    @RequestMapping("addcar")
    public Message addCar(Model model, HttpServletRequest request, @RequestParam("bookid") int bookid){
        Message message = new Message();
        String username = (String)request.getSession().getAttribute("username");
        if(username == null){
            message.setMessage("false");
            message.setUrl("login1");
            model.addAttribute("message","请先登录");
            return message;
        }
        int userid = (Integer) request.getSession().getAttribute("userid");
        OrdersModel ordersModel = new OrdersModel();
        ordersModel.setUserId(userid);
        ordersModel.setOrderDate(new Date());
        OrderItemModel orderItemModel = new OrderItemModel();
        orderItemModel.setBookId(bookid);
        orderItemModel.setQuantity(1);
        int i = cartService.addOrder(ordersModel,orderItemModel);
        if(i>0){
            message.setMessage("true");
            return message;
        }else{
            message.setMessage("false");
            return  message;
        }
    }
}
